<?php

/**
 * Created by PhpStorm.
 * User: huyi
 * Date: 2018/1/16
 * 建立消息队列基础类
 */
class Queue{
    // 交换机名称
    protected $exchangeName = 'ex_auto_home';
    //队列名称
    protected $queueName = 'qu_auto_home';
    //路由名称
    protected $routeName = 'ru_auto_home';

    protected $_connectHandler;

    protected $_channelObject;

    protected $_exchangeObject;

    protected $_queueObject;

    protected $config = array(
        'host'     => '127.0.0.1',
        'port'     => 5672,
        'vhost'    => '/',
        'login'    => 'huyi',
        'password' => 'huyi123'
    );

    //构造函数，依次创建通道，交换机，队列
    public function __construct(){
        try{
            $this->_connectHandler = new AMQPConnection($this->config);
            if(!$this->_connectHandler->connect()){
                die('connect failed');
            }
            $this->createChannel(); //创建通道
            $this->createExchange(); //创建交换机
            $this->createQueue();    //创建队列
        }
        catch(Exception $e){
            echo $e->getMessage();
        }
    }

    //创建通道
    public function createChannel(){
        $this->_channelObject = new AMQPChannel($this->_connectHandler);
    }

    //创建交换机
    public function createExchange($exchangeName = '',$exchangeType = AMQP_EX_TYPE_DIRECT){
        $exchangeName = $exchangeName ? $exchangeName : $this-> exchangeName;
        $this -> _exchangeObject = new AMQPExchange($this -> _channelObject);
        $this -> _exchangeObject -> setName($exchangeName);
        $this -> _exchangeObject -> setType($exchangeType);
        $this->_exchangeObject->setFlags(AMQP_DURABLE | AMQP_AUTODELETE);
        $this->_exchangeObject->declareExchange();
    }

    //创建队列
    public function createQueue(){
        $this->_queueObject = new AMQPQueue($this->_channelObject);
        $this->_queueObject->setName($this-> queueName);
        $this->_queueObject->setFlags(AMQP_DURABLE | AMQP_AUTODELETE);
        $this->_queueObject->declareQueue();
        $this->_queueObject->bind($this->_exchangeObject->getName(), $this->routeName);
    }
}
